package cn.topcodes.tcsf.admin.commons.api.other;

import cn.topcode.unicorn.utils.IgnoreException;
import cn.topcode.unicorn.utils.RenderUtil;
import cn.topcode.unicorn.utils.StringUtil;
import cn.topcode.unicorn.utils.ValidationException;
import cn.topcodes.tcsf.admin.commons.api.domain.ApiResponseEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.persistence.EntityNotFoundException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class UniformExceptionHandler implements HandlerExceptionResolver {

    private static Logger logger = LoggerFactory.getLogger(UniformExceptionHandler.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
                                         Exception ex) {

        ModelAndView mav = new ModelAndView();
        String contentType = request.getHeader("accept");
        if(StringUtil.isBlank(contentType)|| contentType.contains(MediaType.TEXT_HTML_VALUE)) {
            if(ex instanceof IgnoreException) {
                if(StringUtil.isBlank(ex.getMessage())) {
                    logger.warn(ex.getMessage());
                }
            }else {
                logger.error("服务器内部发生错误", ex);
            }
            mav.setViewName("error/500");
        }else {
            ApiResponseEntity apiResponseEntity = null;
            if(ex instanceof IgnoreException) {
                if(StringUtil.isBlank(ex.getMessage())) {
                    logger.warn(ex.getMessage());
                }
            }else if(ex instanceof EntityNotFoundException) {
                apiResponseEntity = ApiResponseEntity.buildNotFound(ex.getMessage());
            }else if(ex instanceof ValidationException || ex instanceof IllegalArgumentException) {
                apiResponseEntity = ApiResponseEntity.buildIllegalArgument(ex.getMessage());
            }else if(ex.getMessage() != null && ex.getMessage().contains("Duplicate entry")) {
                logger.error("服务器内部发生错误", ex);
                apiResponseEntity = ApiResponseEntity.buildIllegalArgument("提交数据已存在");
            }else if(ex.getMessage() != null && ex.getMessage().contains("Broken pipe")) {
                apiResponseEntity = ApiResponseEntity.buildIllegalArgument("客户端请求中断");
            }else if(ex.getMessage() != null && ex.getMessage().contains("Data too long for column")) {
                logger.error("服务器内部发生错误", ex);
                apiResponseEntity = ApiResponseEntity.buildIllegalArgument("提交数据长度过大");
            }else if(ex.getClass().getSimpleName().contains("ClientAbortException")) {
                apiResponseEntity = ApiResponseEntity.buildIllegalArgument("客户端主动断开连接");
            } else {
                logger.error("服务器内部发生错误", ex);
                apiResponseEntity = ApiResponseEntity.buildFailed("服务器内部发生错误");
            }
            response.setStatus(HttpStatus.OK.value()); //设置状态码
            /*response.setContentType(MediaType.APPLICATION_JSON_VALUE); //设置ContentType*/
            response.setCharacterEncoding("UTF-8"); //避免乱码
            response.setHeader("Cache-Control", "no-cache, must-revalidate");

            try {
                RenderUtil.renderJson(apiResponseEntity,response);
            } catch (Exception e) {
//                logger.warn("服务器内部发生错误", e);
            }
        }
        return mav;
    }
}  